package stc.skymobi.netty.handler.codec.memcached;

import com.google.common.cache.Cache;
import io.netty.channel.Channel;

import org.apache.commons.collections.Closure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stc.skymobi.netty.handler.codec.memcached.bean.request.BinaryRequestHeader;

import java.util.concurrent.BlockingQueue;

public class RequestSender implements Runnable {
    private static Logger logger = LoggerFactory.getLogger(RequestSender.class);

    // pool instance
    private ChannelPool pool;
    private BlockingQueue<BinaryRequestHeader> requestQueue;

    // optional error handler
    protected ErrorHandler errorHandler;

    private Cache<Integer, Closure> uuidCache;

    public void run() {
        Channel channel = null;
        while (true) {
            try {
                BinaryRequestHeader request = requestQueue.take();
                if (request.getKey() != null) {
                    // get Channel obj
                    channel = pool.getChannel(request.getKey(), request.getHashCode());
                    // write the buffer to server
                    // now write the data to the cache server
                    uuidCache.put(request.getOpaque(), request.getCallback());
                    if (channel == null) {
                        logger.error("no channel to server available");
                    } else {
                        channel.writeAndFlush(request);
                    }
                }

            } catch (Exception e) {
                logger.error("", e);
            } /*finally {
                if(channel != null)
                    pool.returnChannel(channel);
            }*/

        }
    }

    public void setPool(ChannelPool pool) {
        this.pool = pool;
    }

    public BlockingQueue<BinaryRequestHeader> getRequestQueue() {
        return requestQueue;
    }

    public void setRequestQueue(BlockingQueue<BinaryRequestHeader> requestQueue) {
        this.requestQueue = requestQueue;
    }

    public void setUuidCache(Cache<Integer, Closure> uuidCache) {
        this.uuidCache = uuidCache;
    }
}
